﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

namespace LibGlobal
{
    public class Export
    {
        public static void ExcelExport(DataTable data, string outputfile, string template)
        {
            XmlDocument document;
            int num;
            int count;
            var str8 = template;
            switch (str8)
            {
                case null:
                case "":
                    return;

                default:
                    {
                        document = new XmlDocument();
                        document.Load(template);
                        var node = document.GetElementsByTagName("Worksheet")[0];
                        var s = "";
                        num = 0;
                        count = 0;
                        var list = new List<XmlNode>();
                        foreach (XmlNode node3 in node.ChildNodes)
                        {
                            if (node3.Attributes == null ||
                                ((node3.Attributes["name"] == null) || (node3.Attributes["name"].Value != "tabledata")))
                                continue;
                            var node2 = node3;
                            var xmlNodeList = node3.SelectNodes("*");
                            if (xmlNodeList != null)
                                foreach (XmlNode node5 in xmlNodeList)
                                {
                                    var refChild = node5;
                                    if (node5.Attributes != null && node5.Attributes["name"] != null)
                                    {
                                        str8 = node5.Attributes["name"].Value;
                                        if (str8 != null)
                                        {
                                            if (str8 != "rowtempletegroup")
                                            {
                                                if (str8 == "rowtemplete")
                                                {
                                                    goto Label_016E;
                                                }
                                            }
                                            else
                                            {
                                                s = node5.OuterXml;
                                                node2.RemoveChild(node5);
                                                num--;
                                            }
                                        }
                                    }
                                    continue;
                                Label_016E:
                                    var str2 = node5.OuterXml;
                                    if (node2.Attributes != null)
                                    {
                                        node2.Attributes.Remove(node2.Attributes["ss:ExpandedRowCount"]);
                                        document.CreateAttribute("ss:ExpandedRowCount");
                                        XmlNode node7;
                                        if (node5.Attributes["dataxml"] != null)
                                        {
                                            var document2 = new XmlDocument();
                                            document2.LoadXml("<root>" + data.Rows[0][node5.Attributes["dataxml"].Value] + "</root>");
                                            foreach (var node6 in document2.ChildNodes[0].Cast<XmlNode>().Where(node6 => node6.Name == "obj"))
                                            {
                                                count++;
                                                node7 = document.ReadNode(new XmlTextReader(new StringReader(str2)));
                                                if (node7 == null) continue;
                                                foreach (XmlNode node8 in node7.ChildNodes)
                                                {
                                                    foreach (XmlNode node9 in node6.ChildNodes)
                                                    {
                                                        if (node9.Name == "RepairItemGroupName")
                                                        {
                                                            var flag = false;
                                                            var node91 = node9;
                                                            foreach (var node10 in list.Where(node10 => node10.Attributes != null && node10.Attributes["RepairItemGroupName"].Value == node91.InnerText))
                                                            {
                                                                flag = true;
                                                                refChild = node10;
                                                                break;
                                                            }
                                                            if (!flag)
                                                            {
                                                                num++;
                                                                var item = document.ReadNode(new XmlTextReader(new StringReader(s)));
                                                                var attribute2 = document.CreateAttribute("RepairItemGroupName");
                                                                attribute2.Value = node9.InnerText;
                                                                if (item != null)
                                                                {
                                                                    if (item.Attributes != null)
                                                                    {
                                                                        item.Attributes.Append(attribute2);
                                                                        var node92 = node9;
                                                                        foreach (var node12 in item.ChildNodes.Cast<XmlNode>().Where(node12 => node12.Attributes != null && (((node12.Attributes["name"] != null) && (node12.Attributes["name"].Value == node92.Name)))))
                                                                        {
                                                                            node12.ChildNodes[0].InnerText = node9.InnerText;
                                                                            break;
                                                                        }
                                                                        list.Add(item);
                                                                        node2.InsertBefore(item, refChild);
                                                                        item.Attributes.Remove(item.Attributes["xmlns"]);
                                                                        item.Attributes.Remove(item.Attributes["xmlns:ss"]);
                                                                        item.Attributes.Remove(item.Attributes["name"]);
                                                                    }
                                                                    refChild = item;
                                                                }
                                                            }
                                                        }
                                                        if (((node8.Attributes["name"] == null) ||
                                                             (node8.Attributes["name"].Value != node9.Name)) ||
                                                            (node9.InnerText == null)) continue;
                                                        node8.ChildNodes[0].InnerText = node9.InnerText;
                                                        break;
                                                    }
                                                }
                                                node2.InsertAfter(node7, refChild);
                                                node7.Attributes.Remove(node7.Attributes["xmlns"]);
                                                node7.Attributes.Remove(node7.Attributes["xmlns:ss"]);
                                                node7.Attributes.Remove(node7.Attributes["name"]);
                                            }
                                        }
                                        else
                                        {
                                            foreach (DataRow row in data.Rows)
                                            {
                                                node7 = document.ReadNode(new XmlTextReader(new StringReader(str2)));
                                                foreach (DataColumn column in data.Columns)
                                                {
                                                    var column1 = column;
                                                    foreach (var node8 in node7.ChildNodes.Cast<XmlNode>().Where(node8 => node8.Attributes != null && ((node8.Attributes["name"] != null) && (node8.Attributes["name"].Value == column1.ColumnName))))
                                                    {
                                                        node8.ChildNodes[0].InnerText = row[column].ToString();
                                                    }
                                                }
                                                node2.InsertAfter(node7, node5);
                                                node7.Attributes.Remove(node7.Attributes["xmlns"]);
                                                node7.Attributes.Remove(node7.Attributes["xmlns:ss"]);
                                                node7.Attributes.Remove(node7.Attributes["name"]);
                                            }
                                            count = data.Rows.Count;
                                        }
                                    }
                                    node2.RemoveChild(node5);
                                    count--;
                                }
                            break;
                        }
                        break;
                    }
            }
            var innerXml = document.InnerXml;
            const string pattern = @"=SUM\(R\[\-([0-9]+)\]";
            var match = Regex.Match(innerXml, pattern, RegexOptions.IgnoreCase);
            var replacement = "";
            if (match.Success)
            {
                var num3 = Convert.ToInt32(match.Groups[1].Value);
                replacement = "=SUM(R[-" + ((num3 + count) + num) + "]";
            }
            document.InnerXml = Regex.Replace(document.InnerXml, pattern, replacement);
            if (data.Rows.Count > 0)
            {
                foreach (DataColumn column in data.Columns)
                {
                    document.InnerXml = document.InnerXml.Replace("{" + column.ColumnName + "}", data.Rows[0][column].ToString());
                }
            }
            outputfile = outputfile.Replace(".pdf", ".xls");
            document.Save(outputfile);
            //HttpContext.Current.Response.Clear();
            //HttpContext.Current.Response.ContentType = "text/plain";
            //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + outputfile);
        }
        public static void DownloadFile(string strURL, string sFileName, string sExtend)
        {
            var req = new WebClient();
            var response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + sExtend + "\"");
            byte[] data = req.DownloadData(HttpContext.Current.Server.MapPath(strURL));
            response.BinaryWrite(data);
            response.End();
        }
    }
}